﻿using Cysharp.Threading.Tasks;
using Net.System;
using System.Net.Sockets;

namespace SocketTest
{
    internal class Client
    {
        private const int ConnectionCount = 50000;
        public ListSafe<Socket> clients = new();

        public async void Start()
        {
            //var tasks = new UniTask[ConnectionCount];
            //for (int i = 0; i < ConnectionCount; i++)
            //{
            //    tasks[i] = UniTask.Run(ConnectToServer);
            //}
            //await UniTask.WhenAll(tasks);
            int connectionCount = 0;
            while (ConnectToServer())
            {
                var tasks = new UniTask<bool>[100];
                for (int i = 0; i < 100; i++)
                {
                    tasks[i] = UniTask.Run(ConnectToServer);
                }
                var result = await UniTask.WhenAll(tasks);
                for (int i = 0; i < result.Length; i++)
                {
                    if (result[i])
                        connectionCount++;
                }
                Console.WriteLine($"连接数量:" + connectionCount);
            }
        }

        private bool ConnectToServer()
        {
            try
            {
                var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
                {
                    NoDelay = true
                };
                client.Connect("192.168.159.128", 5000);
                client.Send(new byte[10]);
                clients.Add(client);
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return false;
            }
        }
    }
}
